package com.android.corestat.utils;

import java.lang.reflect.Method;

import android.app.Service;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

public class SimUtil {

	public static boolean isSimIn(Context ctx) {
		boolean result = false;
		TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Service.TELEPHONY_SERVICE);
		int state = tm.getSimState();
		if(state == TelephonyManager.SIM_STATE_READY) {
			result = true;
		} else if(state == TelephonyManager.SIM_STATE_UNKNOWN) {
			//添加联想双卡手机的SIM插入检测
			try {
				Class<?> cx = Class.forName("android.telephony.MSimTelephonyManager");
				Object obj = ctx.getSystemService("phone_msim");
				if (obj == null) {
					result = false;
				} else {
					Method simState = cx.getMethod("getSimState", int.class);
					int sim1State = (Integer) simState.invoke(obj, 0);
					int sim2State = (Integer) simState.invoke(obj, 1);
					if(sim1State == TelephonyManager.SIM_STATE_READY 
							|| sim2State == TelephonyManager.SIM_STATE_READY) {
						result = true;
					}
				}
			} catch (Exception e) {
			} 
		}
		if (!result) {
			if (!TextUtils.isEmpty(tm.getSubscriberId())){
				result = true;
			}
		}
		CSLog.d("isSimIn", "result=" + result + ",state=" + state + ",imsi=" + tm.getSubscriberId());
		return result;
	}
}
